package uit.jee.lib.access.mapper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import uit.jee.lib.dto.BookTypeDTO;

/**
 *
 * @author ngloc_it
 */
public class BookTypeMapper extends MapperDB{

    public BookTypeMapper() throws Exception {
        super();
    }

    private void InitBookTypeDTOFromRs(BookTypeDTO bookType, ResultSet rs) throws Exception{
        if((rs != null) && (bookType != null)){
            bookType.setId(rs.getString(BookTypeDTO.BOOKTYPE_ID));
            bookType.setName(rs.getString(BookTypeDTO.BOOKTYPE_NAME));
        }
    }

    public ArrayList<BookTypeDTO> GetAllBookType() throws Exception {
        ArrayList<BookTypeDTO> booktypes = new ArrayList<BookTypeDTO>();
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("select * from booklibrary.loaisach");
            PreparedStatement stmt = getConnection().prepareStatement(sql.toString());
            ResultSet re = stmt.executeQuery();
            while (re != null && re.next()) {
                BookTypeDTO booktype = new BookTypeDTO();
                InitBookTypeDTOFromRs(booktype, re);
                booktypes.add(booktype);
            }
        } catch (Exception ex) {
            throw ex;
        }
        return booktypes;

    }

    /**
     * Get type name by it's id
     * @param bookTypeId
     * @return
     * @throws Exception
     */
    public String GetBookTypeName(String bookTypeId) throws Exception {
        String typeName = new String();
        BookTypeDTO booktype = new BookTypeDTO();
        StringBuffer sql = new StringBuffer();
        sql.append("select * ").append(" from booklibrary.loaisach where ");
        sql.append(BookTypeDTO.BOOKTYPE_ID).append("= '").append(bookTypeId).append("'");

        PreparedStatement stmt = getConnection().prepareStatement(sql.toString());
        ResultSet re = stmt.executeQuery();

        if (re != null && re.next()) {
            InitBookTypeDTOFromRs(booktype, re);
            typeName = booktype.getName();
            return typeName;
        }
        return null;

    }
}
